import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:untitleqianru/word_detaile_dialog.dart';

import 'MyDrawer.dart';
import 'favorites.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late GetResultLayout getResultLayout;
  String strResult = "";

  static List<String> langLable = [
    '中文',
    '英语',
    '日语',
    '韩语',
    '法语',
    '俄语',
    '西班牙语',
    '德语',
    '意大利语',
    '葡萄牙语'
  ];
  static List<String> langKey = [
    'zh-CN',
    'en',
    'ja',
    'ko',
    'fr',
    'ru',
    'es',
    'de',
    'it',
    'pt'
  ];
  int langIndexSou = 0;
  int langIndexTar = 1;
  RichTextLay richTextLay = RichTextLay("");
  late DropdownButtonLay dropdownButtonSou;
  late DropdownButtonLay dropdownButtonTar;

  static List<PickerItem<int>> PickerData = [
    PickerItem(text: const Text('中文'), value: 0),
    PickerItem(text: const Text('英语'), value: 1),
    PickerItem(text: const Text('日语'), value: 2),
    PickerItem(text: const Text('韩语'), value: 3),
    PickerItem(text: const Text('法语'), value: 4),
    PickerItem(text: const Text('俄语'), value: 5),
    PickerItem(text: const Text('西班牙语'), value: 6),
    PickerItem(text: const Text('德语'), value: 7),
    PickerItem(text: const Text('意大利语'), value: 8),
    PickerItem(text: const Text('葡萄牙语'), value: 9),
  ];

  void setSouIndex(int value) {
    if (langIndexTar == value) {
      langIndexTar = langIndexSou;
      dropdownButtonTar.reload(langLable[langIndexTar]);
    }
    langIndexSou = value;
  }

  void shoeToast(String str) {
    Fluttertoast.showToast(
        msg: str,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.grey,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  void setTarIndex(int value) {
    if (langIndexSou == value) {
      langIndexSou = langIndexTar;
      dropdownButtonSou.reload(langLable[langIndexSou]);
    }
    langIndexTar = value;
  }

  void setGetResultLayout(GetResultLayout value) {
    getResultLayout = value;
  }

  void dayin(String s1, String s2) {
    print("dayin!!!!!!!!");
    print(s1);
    print(s2);
    richTextLay.reload(s1);
    strResult = s1;
  }

// 阴影效果
  BoxShadow MyBoxShadow() {
    return const BoxShadow(
        color: Colors.white10,
        offset: Offset(2.0, 2.0),
        // blurStyle: BlurStyle.inner,
        blurRadius: 5.0);
  }


  @override
  Widget build(BuildContext context) {
    String conditionName = "";
    int conditionNameLength = 0;
    _MyHomePageState _myHomePageState = this;
    dropdownButtonSou = DropdownButtonLay(this, "源", "中文");
    dropdownButtonTar = DropdownButtonLay(this, "目标", "英文");
    const icons = [Icons.arrow_back_outlined, Icons.arrow_forward_outlined];

    TextEditingController _unameController = TextEditingController();
    FocusNode _commentFocus = FocusNode();
    TextField textField = TextField(
      focusNode: _commentFocus,
        autofocus: false,
        minLines: 3,
        maxLines: 10,
        controller: _unameController,
        decoration: const InputDecoration(
          labelText: "请输入翻译内容",
        ),

        onChanged: (text) {
          //内容改变的回调
          conditionName = text;
          conditionNameLength = text.length;
        });


    // FunctionPage functionPage = FunctionPage();
    return Scaffold(
        // endDrawer: SmartDrawer(), //抽屉
        body: Container(
            child: ListView(shrinkWrap: true, children: [
              Container(
                margin: EdgeInsets.all(10.0),
              ),
      Card(
        margin: EdgeInsets.all(8.0),
        elevation: 1.0,
        child: Container(
          margin: EdgeInsets.all(10.0),
          decoration: BoxDecoration(boxShadow: [MyBoxShadow(), MyBoxShadow()]),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Expanded(child: dropdownButtonSou),
                ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    // child: typeList[this.data.caseTypeId],
                    child: IconButton(
                        icon: Icon(
                          icons[1],
                          color: Colors.blue,
                          // semanticLabel: "user",
                          size: 30.0,
                        ),
                        onPressed: () {
                          var tmp = langIndexSou;
                          langIndexSou = langIndexTar;
                          langIndexTar = tmp;
                          dropdownButtonSou.reload(langLable[langIndexSou]);
                          dropdownButtonTar.reload(langLable[langIndexTar]);
                        })),
                Expanded(child: dropdownButtonTar),
              ]),
        ),
      ),
      Card(
        margin: EdgeInsets.all(8.0),
        elevation: 3.0,
        child: Container(
          margin: EdgeInsets.all(10.0),
          decoration: BoxDecoration(boxShadow: [MyBoxShadow(), MyBoxShadow()]),
          child: textField,
        ),
      ),
      //caseNameLay1
      Row(
        children: [
          Container(
            margin: EdgeInsets.all(7.0),
          ),
          TextButton(
            child: const Text('翻译', style: TextStyle(fontSize: 18)),
            onPressed: () {

              if (conditionNameLength != 0) {
                _commentFocus.unfocus();
                getResultLayout.reloadUrl(
                    conditionName,
                    langKey[langIndexSou].toString(),
                    langKey[langIndexTar].toString());
              }
              else{
                shoeToast("还未输入原文哦~");
              }
            },
          ),
          // playFayin
          TextButton(
            child: const Text("清空", style: TextStyle(fontSize: 17)),
            onPressed: () {
              print("清空");
              conditionNameLength = 0;
              _unameController.clear();
              richTextLay.reload("");
            },
          ),
          TextButton(
            child: const Text("朗读", style: TextStyle(fontSize: 17)),
            onPressed: () {
              if (conditionNameLength != 0) {
                getResultLayout.playFayin();
              }
              else{
                shoeToast("还没进行翻译呢~");
              }
            },
          ),
          TextButton(
            child: const Text("复制", style: TextStyle(fontSize: 17)),
            onPressed: () {
              if (conditionNameLength != 0) {
                Clipboard.setData(ClipboardData(text: strResult));
                shoeToast("已复制到剪切板");
              }
              else{
                shoeToast("还没进行翻译呢~");
              }
            },
          ),
          TextButton(
            child: const Text("收藏夹", style: TextStyle(fontSize: 17)),
            onPressed: () {
              FavoritesDialog().build1(context);
            },
          )
        ],
      ),
      Card(
        margin: EdgeInsets.all(8.0),
        elevation: 3.0,
        child: Container(
          margin: EdgeInsets.all(10.0),
          decoration: BoxDecoration(boxShadow: [MyBoxShadow(), MyBoxShadow()]),
          child: richTextLay,
        ),
      ),

      Container(
        height: 1,
        width: 4,
        child: GetResult(_myHomePageState),
      ),
    ])));
  }
}

class GetResult extends StatefulWidget {
  late String nameTmp;
  late _MyHomePageState _myHomePageState;

  GetResult(_MyHomePageState myHomePageState) {
    _myHomePageState = myHomePageState;
  }

  @override
  State<StatefulWidget> createState() {
    return GetResultLayout(_myHomePageState);
  }
}

class GetResultLayout extends State<GetResult> {
  late _MyHomePageState _myHomePageState;

  GetResultLayout(_MyHomePageState myHomePageState) {
    _myHomePageState = myHomePageState;
    _myHomePageState.setGetResultLayout(this);
  }

  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  // List<String> strRes = {"", ""} as List<String>;
  String strRes1 = "";
  String strRes2 = "";
  String keyText = "";
  final urlController = TextEditingController();
  //

  void reloadUrl(String keyText, String sou, String tar) {
    this.keyText = keyText;

    URLRequest request = URLRequest(
      url: Uri.parse("http://xiaoa.win/?sl=" +
          sou +
          "&tl=" +
          tar +
          "&text=" +
          keyText),
    );
    webViewController?.loadUrl(urlRequest: request);
    check();
  }

  void playFayin(){

    webViewController
        ?.evaluateJavascript(
        source: 'document.getElementsByClassName(\'Tw0Tv\')[0].click();').then((value2) {
      print("fayin");
      print(value2);
    });
  }
  //  document.getElementsByClassName('dic-basic-voice')[0].getElementsByTagName('img');
  // Q4iAWc  NqnNQd VfPpkd-Bz112c-LgbsSe VfPpkd-Bz112c-LgbsSe-OWXEXe-e5LLRc-SxQuSe fzRBVc tmJved DiOXab SSgGrd Tw0Tv m0Qfkd
  int getResult(int i) {
    webViewController
        ?.evaluateJavascript(
            source: 'document.getElementsByClassName(\'Q4iAWc\')[' +
                i.toString() +
                '].innerHTML;')
        .then((value2) {
      print("value2");
      print(value2);
      if (value2 != null) {
        strRes1 = strRes1 + value2;
        // if (i % 2 == 0) {
        //   strRes1 = strRes1 + value2;
        // } else {
        //   strRes2 = strRes2 + value2;
        // }

        getResult(i + 1);
      } else {
        if (i > 0) {
          _myHomePageState.dayin(strRes1, strRes2);
        } else {
          check();
        }
      }
    });

    return -1;
  }

  void check() {
    Stream.fromFuture(Future.delayed(
      const Duration(milliseconds: 500),
    ))
        .listen(
      (event) {},
    )
        .onDone(() {
      //500ms后执行这里
      strRes1 = "";
      strRes2 = "";
      getResult(0);
    });
  }

  Widget build(BuildContext context) {
    return InAppWebView(
      key: webViewKey,
      initialUrlRequest: URLRequest(
          url: Uri.parse(
              "http://xiaoa.win/?sl=auto&tl=en&text=" + keyText)),
      onWebViewCreated: (controller) {
        print("onWebViewCreated#########################");
        webViewController = controller;
      },
    );
  }
}

class CaseNameLay extends StatefulWidget {
  late String nameTmp;
  void reload(String name) {
    caseNameLayout.reload(name);
  }

  CaseNameLay(this.nameTmp);

  CaseNameLayout caseNameLayout = CaseNameLayout();

  @override
  State<StatefulWidget> createState() {
    caseNameLayout.setCaseNameTitle(this.nameTmp);
    return caseNameLayout;
  }
}

class CaseNameLayout extends State<CaseNameLay> {
  String caseNameTitle = '';

  void setCaseNameTitle(String name) {
    caseNameTitle = name;
  }

  void reload(String name) {
    caseNameTitle = name;
    setState(() {});
  }

  //
  @override
  Widget build(BuildContext context) {
    return Text(caseNameTitle,
        style: const TextStyle(fontSize: 20, decoration: TextDecoration.none));
  }
}



class DropdownButtonLay extends StatefulWidget {
  _MyHomePageState _myHomePageState;
  String type;
  String selected;
  void reload(String index) {
    caseNameLayout.reload(index);
  }

  DropdownButtonLay(this._myHomePageState, this.type, this.selected);

  DropdownButtonLayout caseNameLayout = DropdownButtonLayout();

  @override
  State<StatefulWidget> createState() {
    caseNameLayout.setInit(this._myHomePageState, this.type, this.selected);
    return caseNameLayout;
  }
}

class DropdownButtonLayout extends State<DropdownButtonLay> {
  String type = "asd";
  String selected = "";
  late _MyHomePageState _myHomePageState;
  void setInit(_MyHomePageState _myHomePage, String t, String s) {
    _myHomePageState = _myHomePage;
    type = t;
    selected = s;
  }

  void reload(String name) {
    selected = name;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      child: Text(selected, style: const TextStyle(fontSize: 21)),
      onPressed: () {
        Picker(
            //选择器适配器，用于提供数据和生成小部件
            //适配器中的data类型为PickerItem<String>，所以在getData中我们有声明其类型
            adapter: PickerDataAdapter<int>(data: _MyHomePageState.PickerData),
            //当上一级选择更改时，将子级滚动到第一项
            changeToFirst: true,
            //是否隐藏头部
            hideHeader: false,
            title:
                Text('选择' + type + "语言", style: const TextStyle(fontSize: 18)),
            confirmText: "确认",
            cancelText: "取消",
            onConfirm: (Picker picker, List value) {
              // print(value.toString());
              selected = _MyHomePageState.langLable[value[0]];
              print(picker.adapter.text);
              print(value[0]);
              if (type == "源") {
                print("源语言");
                _myHomePageState.setSouIndex(value[0]);
              } else {
                print("目标语言");
                _myHomePageState.setTarIndex(value[0]);
              }
              reload(selected);
            }).showModal(context);
      },
    );
  }
}



class RichTextLay extends StatefulWidget {
  late String nameTmp;
  void reload(String name) {
    richTextLayout.reload(name);
  }

  RichTextLay(this.nameTmp);

  RichTextLayout richTextLayout = RichTextLayout();

  @override
  State<StatefulWidget> createState() {
    // richTextLayout.setCaseNameTitle(this.nameTmp);
    return richTextLayout;
  }
}

class RichTextLayout extends State<RichTextLay> {
  List<InlineSpan> list = [];

  TextSpan getTextSpan(String text) {
    return TextSpan(
      text: text,
      style: TextStyle(fontSize: 19),
      // 设置点击事件
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          print("点击了123");
          text = text.trim();
          print(text);
          print(text[text.length - 1].toString());
          if(RegExp(r"[a-zA-Z]+").hasMatch(text[text.length - 1]) == false){
            text = text.substring(0, text.length - 1);
          }
          print(text);
          print("点击了");
          CaseDialog().build1(context, text);
          // print(text[text.length - 1].toString().isalpha());
        },
    );
  }

  // void setCaseNameTitle(String name) {
  //
  //   // list = [getTextSpan("翻译结果："),getTextSpan("翻译结果：")];
  // }

  void reload(String name) {
    list = [];
    name = name.replaceAll(".", ". ")
        .replaceAll(",", ", ")
        .replaceAll("?", "? ")
        .replaceAll("!", "! ")
        .replaceAll("\"", "\" ");
    List names = name.split(" ");

    for (int i = 0; i < names.length; i++) {
      list.add(getTextSpan(names[i]));
      list.add(const TextSpan(text: " "));
    }

    // list = [getTextSpan("qqq："),getTextSpan("www：")];
    setState(() {});
  }

  //
  @override
  Widget build(BuildContext context) {
    return Text.rich(
      TextSpan(
        children: list,
      ),
    );
  }
}


